﻿@using System.Reflection
@using AntDesign.TableModels
@inherits BaseComponent
@typeparam TItem where TItem : class, new()

<AntTable TItem="TItem" Context="Context" Resizable="Model.Resizable"
          ScrollX="@Model.FixedWidth" ScrollY="@Model.FixedHeight"
          Criteria="Model.Criteria" Result="Model.Result"
          @bind-SelectedRows="Model.SelectedRows"
          RowKey="Model.RowKey" OnChange="OnChange" OnRowClick="OnRowClick"
          HidePagination="!Model.ShowPager">
    @if (!string.IsNullOrWhiteSpace(Model.SelectType))
    {
        <Selection Type="@Model.SelectType" Align="ColumnAlign.Center" Width="50" Class="kui-table-check" />
    }
    <AutoColumn Table="Model" Item="context" />
    <DataAction Table="Model" Item="context" />
 </AntTable>

@code {
    [Parameter] public TableModel<TItem> Model { get; set; }

    protected override void OnInitialized()
    {
        Model.OnRefresh = RefreshAsync;
        base.OnInitialized();
    }

    public async Task RefreshAsync()
    {
        try
        {
            Model.Result = await Model.OnQuery?.Invoke(Model.Criteria);
            StateChanged();
        }
        catch (Exception ex)
        {
            Logger.Exception(ex);
            if (Error != null)
                await Error.HandleAsync(ex);
        }
    }

    private async Task OnChange(QueryModel<TItem> queryModel)
    {
        if (Model.OnQuery == null)
            return;

        try
        {
            //页码
            Model.Criteria.PageIndex = queryModel.PageIndex;
            Model.Criteria.PageSize = queryModel.PageSize;
            //TODO：表格筛选
            // Model.Criteria.Query.Clear();
            // foreach (var item in queryModel.FilterModel)
            // {
            //     foreach (var filter in item.Filters)
            //     {
            //         var type = GetQueryType(filter.FilterCompareOperator);
            //         Model.Criteria.SetQuery(item.FieldName, type, $"{filter.Value}");
            //     }
            // }
            //排序
            var sorts = queryModel.SortModel.Where(s => !string.IsNullOrWhiteSpace(s.Sort));
            Model.Criteria.OrderBys = sorts.Select(m => GetOrderBy(m)).ToArray();
            Model.Criteria.SumColumns = Model.Columns.Where(c => c.IsSum).Select(c => c.Id).ToList();
            Model.Result = await Model.OnQuery?.Invoke(Model.Criteria);
        }
        catch (Exception ex)
        {
            Logger.Exception(ex);
            if (Error != null)
                await Error.HandleAsync(ex);
        }
    }

    private async void OnRowClick(RowData<TItem> row)
    {
        if (Model.OnRowClick == null)
            return;

        await Model.OnRowClick.Invoke(row.Data);
    }

    private QueryType GetQueryType(TableFilterCompareOperator tableFilter)
    {
        switch (tableFilter)
        {
            case TableFilterCompareOperator.Equals:
                return QueryType.Equal;
            case TableFilterCompareOperator.Contains:
                return QueryType.Contain;
            case TableFilterCompareOperator.StartsWith:
                return QueryType.StartWith;
            case TableFilterCompareOperator.EndsWith:
                return QueryType.EndWith;
            case TableFilterCompareOperator.GreaterThan:
                return QueryType.GreatThan;
            case TableFilterCompareOperator.LessThan:
                return QueryType.LessThan;
            case TableFilterCompareOperator.GreaterThanOrEquals:
                return QueryType.GreatEqual;
            case TableFilterCompareOperator.LessThanOrEquals:
                return QueryType.LessEqual;
            case TableFilterCompareOperator.Condition:
                return QueryType.Batch;
            case TableFilterCompareOperator.NotEquals:
                return QueryType.NotEqual;
            case TableFilterCompareOperator.IsNull:
                return QueryType.Equal;
            case TableFilterCompareOperator.IsNotNull:
                return QueryType.NotEqual;
            case TableFilterCompareOperator.NotContains:
                return QueryType.NotEqual;
            case TableFilterCompareOperator.TheSameDateWith:
                return QueryType.Between;
            default:
                return QueryType.Contain;
        }
    }

    private string GetOrderBy(ITableSortModel model)
    {
        //descend  ascend
        var sort = model.Sort == "descend" ? "desc" : "asc";
        return $"{model.FieldName} {sort}";
    }
}